<template>
  <div class="app-container calendar-list-container">
    <el-form :model="form" :rules="rules" ref="form" label-width="100px">
      <el-form-item label="推荐图片" prop="promotionImage">
        <el-upload class="avatar-uploader" name="imageFile" :headers="requestHeader" :action="uploadImgUrl" :show-file-list="false" :on-success="handleUploadSuccess" :before-upload="beforeUpload" :data="uploadParam">
          <img v-if="form.promotionImage" :src="imgBaseURL + form.promotionImage" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过2M</div>
        </el-upload>
      </el-form-item>
      <el-form-item label="排序" prop="dispOrder">
        <el-input v-model="form.dispOrder" placeholder="请输入排序"></el-input>
      </el-form-item>
      <el-form-item label="推荐位置" prop="promotionType">
        <el-select class="filter-item" v-model="form.promotionType" placeholder="请选择推荐位置">
          <el-option v-for="item in typeOptions" :key="item.promotionType" :label="item.typeName" :value="item.promotionType"> </el-option>
       </el-select>
      </el-form-item>      
      <el-form-item v-if="dialogStatus == 'update'">
        <el-button type="primary" v-if="promotionManager_btn_edit" @click="onUpdate('form')">更新</el-button>
        <el-button @click="onCancel('form')">取消</el-button>
      </el-form-item>
      <el-form-item v-if="dialogStatus == 'create'">
        <el-button type="primary" v-if="promotionManager_btn_add" @click="onCreate('form')">保存</el-button>
        <el-button @click="onCancel('form')">取消</el-button>
      </el-form-item>      
    </el-form>
  </div>
</template>
<script>
import {
  addObj,
  getObj,
  putObj,
  getPromotionTypeList
} from 'api/shop/goods/promotion/index';
import { mapGetters } from 'vuex';
import { getToken } from 'utils/auth';
import { isInteger} from 'utils/validate';
export default {
  name: 'promotion',
  data() {
    return {
      imgBaseURL: this.GLOBAL.imgBaseURL,
      form: {
        title: undefined,
        simpleTitle: undefined,
        dispOrder: 1,
        promotionImage: undefined,
        titleImage: undefined,
        goodsId: 0,
        promotionType: undefined
      },
      rules: {
        promotionImage: [
          {
            required: true,
            message: '请选择推荐图片',
            trigger: 'blur'
          }
        ],
        dispOrder: [
          {
            pattern: /^\d{1,4}$/,
            required: true,
            message: '请输入1-4位数字',
            trigger: 'blur'
          }
        ],
        promotionType: [
          {
            required: true,
            message: '请选择推荐位置',
            trigger: 'blur'
          }
        ]    
      },
      total: null,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        goodsName: undefined,
        shopsName: undefined,
        promotionType: undefined,
        orderBy: undefined,
      },
      typeOptions: [],
      promotionManager_btn_edit: false,
      promotionManager_btn_del: false,
      promotionManager_btn_add: false,
      promotionId: 0,
      goodsId: 0,
      dialogStatus: '',
      uploadImgUrl: this.GLOBAL.uploadImgUrl,
      imageUrl:'',
      requestHeader:{"token":getToken()},
      uploadParam:{"useType":"promotion"}
    }
  },
  created() {
    this.promotionManager_btn_edit = this.elements['promotionManager:btn_edit'];
    this.promotionManager_btn_del = this.elements['promotionManager:btn_del'];
    this.promotionManager_btn_add = this.elements['promotionManager:btn_add'];
    this.getPromotionTypeList();
  },
  computed: {
    ...mapGetters([
      'elements'
    ])
  },
  methods: {
    onCreate(formName) {
      this.form.goodsId = this.goodsId;
      this.$refs.form.validate(valid => {
        if (valid) {
          addObj(this.form).then(response =>  {
              if(response.status === 0){
                this.$notify({
                  title: '成功',
                  message: '创建成功',
                  type: 'success',
                  duration: 2000
                });
                this.$emit('closePromotionDialog');
              }
              else{
                this.$message.error(response.message);
                return false;
              }
            })
        } else {
          return false;
        }
      });
    },
    onCancel(formName) {
      const set = this.$refs;
      set[formName].resetFields();
      this.$emit('closePromotionDialog');
    },
    onUpdate(formName) {
      const set = this.$refs;
      set[formName].validate(valid => {
        if (valid) {
          putObj(this.promotionId, this.form).then(() => {
            this.$emit('closePromotionDialog');
            this.$emit('getList');
            this.$notify({
              title: '成功',
              message: '修改成功',
              type: 'success',
              duration: 2000
            });
          });
        } else {
          return false;
        }
      });
    },
    resetTemp() {
      this.form = {
        title: undefined,
        simpleTitle: undefined,
        dispOrder: 1,
        promotionImage: undefined,
        titleImage: undefined,
        goodsId: 0,
        promotionType: undefined
      };
    },
    getFormData(){
      // console.log('promotionId=' + this.promotionId);
      getObj(this.promotionId).then(response => {
          // console.log(response);
          if(response.status === 0){
            this.form = response.data;
          }
          else{
             this.$message.error('查询失败');
          }
      });
    },
    getPromotionTypeList() {
      getPromotionTypeList()
        .then(response => {
          this.typeOptions = response.data;
        })
    },       
    handleUploadSuccess(res, file) {
        if(res === undefined || res.status === undefined || res.status !== 0){
          this.$message.error('图片上传失败！');
        }
        else{
          this.$message.success('图片上传成功！');
          this.imageUrl = URL.createObjectURL(file.raw);
          this.form.promotionImage = res.data;
        }
    },
    beforeUpload(file) {
        const isJPG = (file.type === 'image/jpeg' || file.type === 'image/jpg' || file.type === 'image/png');
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isJPG || !file.type) {
          this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return (isJPG) && isLt2M;
    }
  }
}
</script>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }
  .avatar {
    width: 100px;
    height: 100px;
    display: block;
  }
</style>